<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    border
    v-if="tableData.length > 0"
    @row-click="handleRowClick">
    <el-table-column label="图片">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <img :src="scope.row.encode_img" style="width: 100px; height: 100px">
        </div>
      </template>
    </el-table-column>
    <el-table-column label="图片名称" prop="name"></el-table-column>
  </el-table>
  <el-pagination background layout="prev, pager, next" :total="total_count" :page-size="PAGE_SIZE"
    :current-page="current_page" @update:current-page="handlePageChange" />
</template>

<script lang="ts" setup>
import axios from 'axios'
import { ref, onMounted, type Ref } from 'vue'
import { SERVER_URL } from '@/components/handleApp'
import { useRouter } from 'vue-router'
import { type ImageDict } from '@/components/handleDetect'
/**接口 */

/**变量 */
// 分页相关变量
const current_page = ref(1)
const total_count = ref(40)
const PAGE_SIZE = ref(4)
const tableData: Ref<ImageDict[]> = ref([])
// 路由
const router = useRouter()

/**函数 */
/**
 * 分页变化时更新页码和展示数据
 * @param newVal 新页码
 */
function handlePageChange(newVal: number) {
  current_page.value = newVal
  updatePageData(newVal)
}

/**
 * 获取总记录数量
 */
function updateTotalCount() {
  axios.get(`${SERVER_URL}/detect/get-page-images/`, {
    params: {
      page_size: PAGE_SIZE.value,
      current_page: 0,  // 要获取总数量时，当前页码为0
    }
  })
    .then((res) => {
      total_count.value = res.data.count
    })
    .catch((err) => {
      console.log(err)
    })
}

/**
 * 更新分页数据
 * @param newPage 新页码
 */
function updatePageData(newPage: number) {
  axios.get(`${SERVER_URL}/detect/get-page-images/`, {
    params: {
      page_size: PAGE_SIZE.value,
      current_page: current_page.value,
    }
  })
    .then((res) => {
      tableData.value = res.data.list
      for (const item of tableData.value) {
        item.encode_img = `data:image/jpeg;base64,${item.encode_img}`
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

/**
 * 行点击事件
 * @param row 行数据
 */
function handleRowClick(row: ImageDict, column: any, event:any) {
  router.push({
    path: "/detect",
    query: {
      img_name: row.name
    }
  })
}

onMounted(() => {
  updateTotalCount()
  updatePageData(current_page.value)
})
</script>